<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>clip探照灯</title>
</head>
<body>
<canvas id="canvas">该浏览器不支持</canvas>
</body>
<script>
    var WIDTH = 800;
    var HEIGHT = 800;
    var ball = {
        x:getRandom(100,700),
        y:getRandom(100,700),
        r:100,
        vx:getRandom(4,7),
        vy:getRandom(3,5)
    };
    window.onload = function () {
        var canvas = document.getElementById("canvas");
        canvas.width = WIDTH;
        canvas.height = HEIGHT;
        var cxt = canvas.getContext('2d');
        setInterval(function () {
            draw(cxt);
            update();
        },20);
    };

    /*
    * 绘制所有区域
    * */
    function draw(cxt) {
        cxt.clearRect(0,0,WIDTH,HEIGHT);
        cxt.save();
        //绘制背景
        drawBg(cxt);
        //绘制圆形clip
        drawClip(cxt);
        //绘制文字
        drawText(cxt);
        cxt.restore();
    }
    /*
    * 绘制背景
    * */
    function drawBg(cxt) {
        cxt.beginPath();
        cxt.fillStyle = "black";
        cxt.fillRect(0,0,WIDTH,HEIGHT);
    }

    /*
    * 绘制圆形clip
    * */
    function drawClip(cxt) {
        cxt.beginPath();
        cxt.arc(ball.x,ball.y,ball.r,0,2*Math.PI);
        cxt.fillStyle = "#fff";
        cxt.fill();
        cxt.clip();
    }

    /*
    * 绘制文字
    * */
    function drawText(cxt) {
        cxt.beginPath();
        cxt.fillStyle = "#058";
        cxt.font = "bold 150px Arial";
        cxt.textAlign = "center";
        cxt.textBaseline = "middle";
        cxt.fillText("CANVAS",WIDTH/2,HEIGHT*0.3);
        cxt.fillText("CANVAS",WIDTH/2,HEIGHT*0.6);
        cxt.fillText("CANVAS",WIDTH/2,HEIGHT*0.9);
    }

    /*
    * 运动
    * */
    function update() {
        ball.x += ball.vx;
        ball.y += ball.vy;
        if(ball.x<=ball.r){
            ball.x = ball.r;
            ball.vx = -ball.vx;
        }
        if(ball.x>=WIDTH-ball.r){
            ball.x = WIDTH - ball.r;
            ball.vx = -ball.vx;
        }
        if(ball.y<=ball.r){
            ball.y = ball.r;
            ball.vy = -ball.vy;
        }
        if(ball.y>=HEIGHT - ball.r){
            ball.y = HEIGHT - ball.r;
            ball.vy = -ball.vy;
        }
    }



    /*
     * 随机数
     * */
    function getRandom(start,end,bool) {
        var diff = end - start;
        if(bool === 0){
            var index = Math.round(Math.random()*diff+start);
        }else {
            var index = Math.random() * diff + start;
        }
        return index;
    }

    /*
     * 随机颜色
     * */
    function getColor() {
        var r = getRandom(0,255,0);
        var g = getRandom(0,255,0);
        var b = getRandom(0,255,0);
        var str = "rgb("+r+","+g+","+b+")";
        return str;
    }
</script>
</html>